package message.preset;

import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import java.util.List;

import message.AbstractMessageParser;
import message.GenericMessageParserSupplier;
import message.MessageParser;
import message.MessageParserSupplier;
import message.util.Step;

public class ArrayMessageParserSupplier implements GenericMessageParserSupplier{


	@Override
	public MessageParserSupplier wrapGeneric(MessageParserSupplier[] suppliers) {
		return new MessageParserSupplier() {
			@Override
			public MessageParser parse(Object obj) {
				return new AbstractMessageParser(obj) {
					private MessageParser[] parsers;
					private int p = 0;
					private Step step = new Step();
					@Override
					public boolean write(ByteBuffer byteBuffer) {
						@SuppressWarnings("unchecked")
						List<? extends Object> list = (List<? extends Object>)object;
						if(step.is(0)) {
							try {
								byteBuffer.putInt(list.size());
							} catch (BufferOverflowException e) {
								return false;
							}
							parsers = new MessageParser[list.size()];
							var s = suppliers[0];
							for(int i = 0; i<list.size(); i++) {
								parsers[i] = s.parse(list.get(i));
							}
							step.done();
						}
						if(step.is(1)) {
							while(p < list.size()) {
								if(parsers[p].write(byteBuffer)) p++;
								else return false;
							}
						}
						return true;
					}
				};
			}
		};
	}

	@Override
	public MessageParser parse(Object obj) {
		return null;
	}

}
